package org.example.system.config;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Collections;

/**
 * CORS 资源共享配置
 * 配置跨域资源共享
 *
 * @author LY
 */
@Configuration
public class CorsConfig {

    private static final String ALL_ORIGINS_PATTERN = "*";
    private static final String ALL_PATHS = "/**";
    private static final int FILTER_ORDER = -101;

    @Bean
    public FilterRegistrationBean<CorsFilter> filterRegistrationBean() {
        CorsConfiguration corsConfiguration = buildCorsConfiguration();
        UrlBasedCorsConfigurationSource source = buildConfigurationSource(corsConfiguration);
        CorsFilter corsFilter = new CorsFilter(source);

        return buildFilterRegistrationBean(corsFilter);
    }

    /**
     * 构建CORS配置
     */
    private CorsConfiguration buildCorsConfiguration() {
        CorsConfiguration config = new CorsConfiguration();
        // 允许任何来源
        config.setAllowedOriginPatterns(Collections.singletonList(ALL_ORIGINS_PATTERN));
        // 允许任何请求头
        config.addAllowedHeader(CorsConfiguration.ALL);
        // 允许任何方法
        config.addAllowedMethod(CorsConfiguration.ALL);
        // 允许凭证
        config.setAllowCredentials(true);
        return config;
    }

    /**
     * 构建配置源
     */
    private UrlBasedCorsConfigurationSource buildConfigurationSource(CorsConfiguration config) {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration(ALL_PATHS, config);
        return source;
    }

    /**
     * 构建过滤器注册Bean
     */
    private FilterRegistrationBean<CorsFilter> buildFilterRegistrationBean(CorsFilter filter) {
        FilterRegistrationBean<CorsFilter> registrationBean = new FilterRegistrationBean<>(filter);
        // 设置过滤器优先级，确保在Spring Security过滤器之前应用
        registrationBean.setOrder(FILTER_ORDER);
        return registrationBean;
    }
}